import {
	genTestUserSig
} from '../debug/GenerateTestUserSig'
import TUIChatEngine, {
	TUIUserService,
	TUIStore,
	StoreName,
	TUIConversationService
} from "@tencentcloud/chat-uikit-engine";
//获取用户等级
import {
	userLevelType
} from '@/common/api/customer.js'

// 获取用户当前显示昵称
import {
	generateName
} from "../components/TUIContact/utils";
// 中文转拼音
import Pinyin from 'js-pinyin'
import {
	accountLoginIm,
	getUserInfoUrl
} from '../utils/request/api/api.js'

import devDomain from './request/http'
// #ifdef APP
const TUICallKit=uni.requireNativePlugin('TencentCloud-TUICallKit');
// #endif

const SDKAppID =devDomain.httpUrl === 'https://ycimnew.yueshuwen.com.cn/'? 1600029032 : 1600026460  


//登录后端接口
const customLogin = (role) => {
	let userInfo = uni.getStorageSync('userInfo')
	let photo = userInfo?.userAvatarUrl
	if (photo) {
		if (/(http|https):\/\/([\w.]+\/?)\S*/.test(photo) === false) {
			photo = getApp().globalData.host + photo
		}
	}
	return new Promise((resolve, reject) => {
		accountLoginIm({
			mobile: userInfo.mobile,
			headImg: photo || '',
			nickname: userInfo.nickname || userInfo.mobile,
			role:role,//,
		}).then(res => {
			if (res.code === 200) {
				 
				uni.setStorageSync('ImToken', res.token)
				resolve(res)
			}
		}).catch(err => {
			uni.hideLoading()
		})
	}).catch((error) => {

	});
}


const IMLoginOut = async () => {
	//切换账号 退出登录
	TUIStore.update(StoreName.CUSTOM, 'IMuserInfo', null)
	uni.removeStorageSync('IMuserInfo')
	uni.removeStorageSync('ImToken')
	await TUIChatEngine.logout()
}
// Im登录
const IMLogin = (res) => {
	return new Promise((resolve, reject) => {
		TUIChatEngine.login({
			SDKAppID: SDKAppID,
			userID: String(res.txUserId),
			// UserSig 是用户登录即时通信 IM 的密码，其本质是对 UserID 等信息加密后得到的密文。
			userSig: res.userSig,
			// 发送图片、语音、视频、文件等富媒体消息，为 true
			useUploadPlugin: true,
			// 本地审核可识别、处理不安全、不适宜的内容,已购买内容审核服务,为 true
			useProfanityFilterPlugin: false,
			framework: `vue2` // 当前开发使用框架 vue2 / vue3
		}).then(res => {
			resolve(res)

		}).catch(error => {
			if (error.code === 70399) {
				// uni.showToast({
				// 	title: "被系统删除的聊天账号，三个月内禁止登录",
				// 	icon: "none",
				// })
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/tabbar/index'
					})
				}, 1000)
				return false
			}
			// uni.showToast({
			// 	title: error.message,
			// 	icon: "none"
			// })
			reject(error)
		})
	}).catch((error) => {

	});
}
const getUserInfo = async (userInfo) => {
	console.log(userInfo, "userInfo getUserInfo个人信息")
	//同步珺璟的个人信息
	let res = await TUIUserService.updateMyProfile({
		nick: userInfo.txNickName,
		avatar: userInfo.headImg,
		// profileCustomField: [{
		// 	key: '', //'Tag_Profile_Custom_groupCre',
		// 	value: userInfo.txNickName || ''
		// }]
	})

	if (res) {
		TUIStore.update(StoreName.CUSTOM, 'IMuserInfo', userInfo)
		uni.setStorageSync('IMuserInfo', res.data)
	}


}
const checkUserInfo = () => {
	let userInfo = uni.getStorageSync('userInfo')
	//没有登录外层
	if (!userInfo) {
		uni.reLaunch({
			url: '/pages/login/login'
		})
		return
	}
	if (!uni.getStorageSync('IMuserInfo')) {
		return
	}
	return new Promise((resolve, reject) => {
		TUIUserService.getUserProfile().then(res => {
			resolve(res)
			console.log(res, "用户状态验证")
		}).catch(error => {
			console.log(error, error.code, "用户状态验证error")
			if (error.code === 70399) {
				uni.showToast({
					title: "被系统删除的聊天账号，三个月内禁止登录",
					icon: "none",
				})
			} else if (error.code === 3003) {
				uni.showToast({
					title: "账号已在其他设备登录，请重新登录",
					icon: "none",
				})
			} else {
				uni.showToast({
					title: error.message,
					icon: "none"
				})
			}

			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			}, 1500)
			reject(error)
		})

	}).catch((error) => {

	});
}
const getUserInfoUrlFun = () => {
	return new Promise((resolve, reject) => {
		getUserInfoUrl().then(res => {
			if (res.code === 200) {
				resolve(res.data)
			}
		}).catch(err => {
			uni.hideLoading()
		})
	}).catch((error) => {

	});
}
//设置语音
const setMusic=async()=>{
	     const downloadResult = await uni.downloadFile({ url:'https://main-pro.yanchaochao.com/mp-static/rain.mp3' }) // 下载文件
	   const tempFilePath = downloadResult[1].tempFilePath // 下载后的临时文件路径
	let musicFilePath = '';
	uni.saveFile({
	    tempFilePath: tempFilePath,
	    success: (res) => {
	      	console.warn('保存文件成功 = ', JSON.stringify(res)); // 获取的是相对路径
	        musicFilePath =  res.savedFilePath;
	        
	        // 【2】相对路径转绝对路径，否则访问不到
	        musicFilePath = plus.io.convertLocalFileSystemURL(musicFilePath); // 转绝对路径
	        
	        // 【3】设置铃声
	        TUICallKit.setCallingBell(musicFilePath, (res) => {
	          if (res.code === 0) {
	            console.log('setCallingBell success,保存音频设置铃声');
	          } else {
	            console.log(`setCallingBell failed, error message = ${res.msg}铃声异常`);
	          }
	        });
	    },
	    fail: (err) => {
	      console.error('保存文件失败',err);
	    },
	});

}
const checkLogin = async () => {
	let userInfo = uni.getStorageSync('userInfo')
	//没有缓存userInfo就是跳转APP的登录页
	if (!userInfo) {
		uni.reLaunch({
			url: '/pages/login/login'
		})
		return
	}
	//初始化
	TUIStore.update(StoreName.CUSTOM, 'IMuserInfo', null)
	let res1=await userLevelType({
		phone:userInfo.mobile
	})
	// if(res1.code!==200){
	// 	return uni.reLaunch({
	// 		url: '/pages/index/index'
	// 	})
	// }
	let res = await customLogin(res1.data)
	if (res.code === 200) {
		let result = await IMLogin(res)
		console.log(result, "result")
		// #ifdef APP
		//语音通话登录
		TUICallKit.login({
			SDKAppID: SDKAppID,
			userID: String(res.txUserId),
		  	userSig: res.userSig,
		}, (res) => {
		  if (res.code === 0) {
			TUICallKit.enableFloatWindow(true);
		  } else {
		    console.log(`login failed, error message = ${res.msg}`);
		  }
		});
		// #endif
		
		if (result) {
			let userInfoRes = await getUserInfoUrlFun()
			console.log(userInfoRes, "userInfoRes")
			if (userInfoRes) {
				// #ifdef APP
				//语音通话设置
				setMusic()
				console.log(userInfoRes,"userInfoRes.headImg")
				TUICallKit.setSelfInfo({
					nickName:userInfoRes.txNickName || '珺璟用户',
					avatar:userInfoRes.headImg || 'https://main-pro.yanchaochao.com/mp-static/IM-head.png',
				}, (res) => {
				  if (res.code === 0) {
				    console.log(res,"设置头像成功了吗");
				  } else {
				    console.log(`setSelfInfo failed, error message = ${res.msg}`);
				  }
				});
				// #endif
				await getUserInfo(userInfoRes)
				
			}
		}

	}
}

const sortByFirstLetter = (origin) => {
	// 将目标数据进行排序
	origin = origin.sort((pre, next) => {
		let keyText = Pinyin.getFullChars(generateName(pre)).charAt(0)
		// 首字母不是字母
		if (!uni.$u.test.letter(keyText)) {
			keyText = '*'
		}
		// 让星排最后
		if (keyText === '*') {
			return 9999
		} else {
			return keyText.localeCompare(Pinyin.getFullChars(generateName(next)))
		}

	})
	const newArr = []
	const charCodeOfA = 'A'.charCodeAt(0);
	for (let i = 0; i < 26; i++) {
		newArr.push({
			key: String.fromCharCode(charCodeOfA + i),
			list: []
		});
	}
	newArr.push({
		key: '*',
		list: []
	})
	console.log(newArr)
	origin.map(item => {
		// 取首字母
		let key = Pinyin.getFullChars(generateName(item)).charAt(0).toUpperCase()
		// 首字母不是字母
		if (!uni.$u.test.letter(key)) {
			key = '*'
		}
		const index = newArr.findIndex(subItem => subItem.key === key)
		console.log(index, key, "当前的")
		newArr[index].list.push(item)

	})
	return newArr
}

export {
	sortByFirstLetter,
	checkLogin,
	IMLoginOut,
	checkUserInfo,
	// #ifdef APP
	TUICallKit
	// #endif
}